package com.scala.zhenghui

import scala.collection.mutable.ArrayBuffer

/**
 * 移除第一个负数以后3个负数
 */
object SuanFaDemo {

  def main(args: Array[String]) {

    //    performanceSlow()
    //    performanceHigh()
    performanceHighTest
  }

  def performanceSlow(): Unit = {
    println()
    val a = ArrayBuffer[Int]()
    a +=(1, 2, 3, 4, 5, -1, -2, -3, -4, -5)
    for (n <- a)
      print(n + ",")
    println()

    var fountFirstNegative = false
    var arrayLength = a.length
    var index = 0
    while (index < arrayLength) {
      if (a(index) >= 0) {
        index += 1
      } else {
        if (!fountFirstNegative) {
          fountFirstNegative = true
          index += 1
        } else {
          a.remove(index)
          arrayLength -= 1
        }
      }
    }
    for (n <- a)
      print(n + ",")
    println()


  }

  def performanceHigh(): Unit = {
    println()
    val a = ArrayBuffer[Int]()
    a +=(1, 2, 3, 4, 5, -1, -2, -3, 4, -5)
    for (n <- a)
      print(n + ",")
    println()


    var fountFirstNegative = false
    val keepIndexes = for (i <- 0 until a.length if !fountFirstNegative || a(i) >= 0) yield {
      if (a(i) < 0) {
        fountFirstNegative = true
      }
      i
    }

    for (n <- keepIndexes)
      print(n + ",")
    println()


    for (i <- 0 until keepIndexes.length) {
      a(i) = a(keepIndexes(i))
    }
    a.trimEnd(a.length - keepIndexes.length)
    for (n <- a)
      print(n + ",")
    println()
  }


  def performanceHighTest(): Unit = {
    println()
    val a = ArrayBuffer[Int]()
    a +=(1, 2, 3, 4, 5, -1, -2, -3, 4, -5)
    for (n <- a)
      print(n + ",")
    println()
    var fountFirstNegative = false
    val keepIndexes = for (i <- 0 until a.length if !fountFirstNegative || a(i) >= 0) yield {
      if (a(i) < 0) {
        fountFirstNegative = true
      }
      i
    }
    for (i <- 0 until keepIndexes.length) {
      a(i) = a(keepIndexes(i))
    }

    a.trimEnd(a.length - keepIndexes.length)
    for (n <- a)
      print(n + ",")
    println()

  }


}
